<template>
  <div class="user-manage-page pd16" v-loading="pageLoading">
    <el-row :gutter="16" class="flex-block">
      <el-col :span="6">
        <el-card class="box-card sp-card">
          <el-tree
            ref="treeRef"
            class="nr-tree"
            :data="treeData"
            :expand-on-click-node="false"
            show-checkbox
            default-expand-all
            node-key="pid"
            highlight-current
            :props="defaultProps"
          />
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card class="box-card sp-card">
          <div class="search-block">
            <el-form ref="searchParamsRef" :model="searchParams" @submit.prevent="search">
              <el-row :gutter="16">
                <el-col :span="8">
                  <el-form-item label="手机号码：" prop="phone">
                    <el-input v-model="searchParams.phone" clearable placeholder="请输入手机号码" style="width: 100%;"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="用户名称：" prop="name">
                    <el-input v-model="searchParams.name" clearable placeholder="请输入用户名称" style="width: 100%;"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item>
                    <el-button type="primary" @click="search">查询</el-button>
                    <el-button @click="reset">重置</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>

          <div class="btn-group">
            <el-button type="primary" @click="addUser">新增用户</el-button>
            <el-button type="primary" @click="batchImport">批量导入用户</el-button>
            <el-button @click="adjustGroup">调整分组</el-button>
          </div>

          <div ref="tableBlockRef" class="data-block mt16 table-block">
            <el-table ref="multipleTableRef" :data="tableData" :max-height="tableHeight" class="nr-table">
              <el-table-column type="selection" width="30"/>
              <el-table-column label="用户名称" prop="username">
                <template #default="scope">
                  <span class="sp-col can-click" @click="handleDetail(scope.row)">{{scope.row.username}}</span>
                </template>
              </el-table-column>
              <el-table-column label="分组" prop="projectName"></el-table-column>
              <el-table-column label="绑定手机" prop="phoneNum">
                <template #default="scope">
                  <span class="sp-col can-click" @click="handleDetail(scope.row)">{{scope.row.phoneNum}}</span>
                </template>
              </el-table-column>
              <el-table-column label="绑定微信" prop="wechatId">
                <template #default="scope">
                  <div style="font-weight: bold;">{{scope.row.wechatId}}</div>
                  <div style="color: #aaa;">{{scope.row.wechatName}}</div>
                </template>
              </el-table-column>
              <el-table-column label="注册时间" prop="regTime">
                <template #default="scope">
                  <span>{{scope.row.regTime ? moment(scope.row.regTime).format('YYYY-MM-DD HH:mm:ss') : ''}}</span>
                </template>
              </el-table-column>
              <el-table-column label="最后登录时间" prop="logInTimeLast">
                <template #default="scope">
                  <span>{{scope.row.logInTimeLast ? moment(scope.row.logInTimeLast).format('YYYY-MM-DD HH:mm:ss') : ''}}</span>
                </template>
              </el-table-column>
              <el-table-column label="绑定设备" prop="deviceBindSum">
                <template #default="scope">
                  <span class="sp-col">{{scope.row.deviceBindSum}}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" fixed="right">
                <template #default="scope">
                  <el-link class="table-btn" type="primary" :underline="false" @click="handleEdit(scope.row)">编辑</el-link>
                  <el-link class="table-btn" type="danger" :underline="false" @click="handleDelete(scope.row)">删除</el-link>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="page-right-block">
            <el-pagination
              class="nr-page"
              v-model:current-page="searchParams.currentPage"
              v-model:page-size="searchParams.pageSize"
              :page-sizes="[10, 20, 30, 40]"
              background
              layout="total, prev, pager, next, sizes, jumper"
              :total="searchParams.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <user-modify-form
      :dialogVisible="modifyFormVis"
      :formStatus="modifyFormStatus"
      :formData="userFormData.data"
      @update:dialogVisible="(value: boolean) => modifyFormVis = value"
      @submit="getUserData">
    </user-modify-form>

    <user-group-dialog
      :dialogVisible="groupDialogVis"
      :formData="userBatchData.data"
      @update:dialogVisible="(value: boolean) => groupDialogVis = value"
      @submit="getUserData">
    </user-group-dialog>

    <user-batch-dialog
      :dialogVisible="batchDialogVis"
      @update:dialogVisible="(value: boolean) => batchDialogVis = value">
    </user-batch-dialog>

    <user-detail-dialog
      :dialogVisible="detailDialogVis"
      :formData="userFormData.data"
      @update:dialogVisible="(value: boolean) => detailDialogVis = value">
    </user-detail-dialog>
  </div>
</template>

<script setup lang="ts" name="UserManage">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import UserModifyForm from './user-modify-form.vue'
import UserGroupDialog from './user-group-dialog.vue'
import UserBatchDialog from './user-batch-dialog.vue'
import UserDetailDialog from './user-detail-dialog.vue'
import { userListPage, userDelete } from '@/api/user-manage'
import { projectList } from '@/api/project-manage'
import moment from 'moment'

const pageLoading = ref(false)
const defaultProps = {
  children: 'projectTree',
  label: 'projectName',
}
const treeRef = ref<any>(null)
const treeData = ref<any>([])
const searchParamsRef = ref<FormInstance>()
const searchParams = reactive({
  name: '',
  phone: '',
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const tableData = ref<any>([])
const tableBlockRef = ref<any>(null)
const tableHeight = ref(200)
const modifyFormVis = ref(false)
const modifyFormStatus = ref(0)
const userFormData = ref({
  data: {}
})
const userBatchData = ref({
  data: []
})
const groupDialogVis = ref(false)
const batchDialogVis = ref(false)
const detailDialogVis = ref(false)

onMounted(() => {
  resizeTable()
  window.addEventListener('resize', resizeTable, false)
  getProjectData()
  getUserData()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeTable, false)
})

// 窗口改变table高度
const resizeTable = () => {
  tableHeight.value = tableBlockRef.value.offsetHeight
}

// 查询
const search = () => {
  searchParams.currentPage = 1
  getUserData()
}

// 重置
const reset = () => {
  searchParamsRef.value?.resetFields()
}

// 分页跳转
const handleCurrentChange = (val: number) => {
  getUserData()
}
const handleSizeChange = (val: number) => {
  getUserData()
}

// 批量导入
const batchImport = () => {
  batchDialogVis.value = true
}

// 调整分组
const adjustGroup = () => {
  let arr = <any>[...multipleTableRef.value?.getSelectionRows()]
  if (arr.length === 0) {
    ElMessage.error(`未选择用户！`)
    return false
  }
  groupDialogVis.value = true
  userBatchData.value.data = <any>[...arr]
}

// 新建
const addUser = () => {
  modifyFormVis.value = true
  modifyFormStatus.value = 0
}

// 编辑
const handleEdit = (row: any) => {
  modifyFormVis.value = true
  modifyFormStatus.value = 1
  userFormData.value.data = Object.assign({}, row)
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除【${row.username}】此用户吗？`,
    '系统提示',
    {
      type: 'warning',
    }
  )
  .then(() => {
    let params = {
      id: row.id
    }
    userDelete(params).then((res: any) => {
      if (res.code === 0) {
        ElMessage.success(`删除成功！`)
        getUserData()
      } else {
        ElMessage.error(`${res.msg}`)
      }
    }).catch(err => {
      console.log(err)
    })
  })
  .catch(() => {})
}

// 详情
const handleDetail = (row: any) => {
  detailDialogVis.value = true
  userFormData.value.data = Object.assign({}, row)
}

// 获取项目树表格数据
const getProjectData = async () => {
  pageLoading.value = true
  await projectList().then((res: any) => {
    if (res.code === 0) {
      treeData.value = [res.data]
      // treeRef.value?.setCheckedKeys([res.data.pid])
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
  pageLoading.value = false
}

// 获取用户表格数据
const getUserData = async () => {
  pageLoading.value = true
  let params = {
    pidList: treeRef.value?.getCheckedKeys(),
    phoneNum: searchParams.phone,
    username: searchParams.name,
    currentPage: searchParams.currentPage,
    pageSize: searchParams.pageSize
  }
  await userListPage(params).then((res: any) => {
    if (res.code === 0) {
      tableData.value = [...res.list]
      searchParams.total = res.page.totalSize
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
  pageLoading.value = false
}
</script>

<style lang="stylus" scoped>
@import '../../style/base.styl'

.user-manage-page
  height 100%
  .sp-col
    color var(--el-color-primary)
  .can-click
    cursor pointer
    &:hover
      opacity .8
  .table-block
    top 106px 
</style>
